/*
 * @Description:
 * @Author: huangmin
 * @Email: 812949176@qq.com
 * @Date: 2023-02-27 09:11:50
 * @LastEditors: huangmin
 * @LastEditTime: 2023-03-02 17:09:35
 * @FilePath: /virtual-list/src/component/VirtualList/utils.js
 */
// 返回最小的一列的下标
export const compareHeight = (heightArr) => {
  return heightArr.indexOf(Math.min(...heightArr));
};

/**
 * @description: 数据定位高度有顺序，使用二分查找优化性能,减少遍历次数
 * @return {*}
 */
export const binarySearch = (list, value) => {
  let start = 0;
  let end = list.length - 1;
  while (start <= end) {
    let midIndex = (start + end) >> 1;
    let midValue =
      list[midIndex].top + list[midIndex].height + list[midIndex].bottomHeight;
    if (midValue >= value) {
      end = midIndex - 1;
    } else {
      start = midIndex + 1;
    }
  }
  if (start>=list.length) {
    return 0;
  }
  return start;
};

/**
 * @description: 获取列表dom距离滚动条容器顶部距离 dom.offsetParent 获取dom元素具有定位属性position的父级元素，递归往上查找，直到找到滚动容器或null
 * @return {*}
 */
export const calcListOffsetTop = (dom, scrollDom, distance) => {
  distance = distance || 0;
  if ([scrollDom, null].includes(dom.offsetParent)) {
    distance += dom.offsetTop;
    return distance;
  } else {
    distance += dom.offsetTop;
    return calcListOffsetTop(dom.offsetParent, scrollDom, distance);
  }
};

// 比较新老数据，判断是否可以使用缓存减少计算
export const comparisonCache = (newData, oldData) => {
  let flag = true;
  if (oldData.length && newData.length > oldData.length) {
    for (let index = oldData.length - 1; index >= 0; index--) {
      const oldItem = oldData[index];
      const newItem = newData[index];
      if (!(oldItem.id === newItem?.id) || !(oldItem.size === newItem.size)) {
        flag = false;
        break;
      }
    }
  } else {
    flag = false;
  }
  return flag;
};
